package cn.pku.ss.fa.ui.component;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.naming.InitialContext;

import org.zkoss.image.Image;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zul.Window;

import cn.pku.ss.fa.sessionbean.UserManagerLocal;
import cn.pku.ss.fa.ui.Common;
import cn.pku.ss.fa.ui.URLStrategy;

/**
 * @author SirX
 */
public class HeadPhotoWindowComponent extends Window {
	
	public HeadPhotoWindowComponent() {
		Session session = Executions.getCurrent().getDesktop().getSession();
		this.userId = (Integer)session.getAttribute(Common.USER_ID);
	}
	
	public String updateHeadPhoto(Image img) {
		String format = img.getFormat();
		String url = URLStrategy.getAlbumRootURL(userId) + "/head." + format;
		
		//create image:
		String path = Common.getWebRootRealPath() + url;
		File imgFile = new File( path );
		try {
			if( imgFile.exists() ) {
				imgFile.delete();
			}
			if( imgFile.createNewFile() ) {
				OutputStream out = new BufferedOutputStream( new FileOutputStream( imgFile ) );
				out.write( img.getByteData() );
				out.flush();
			}
			else {
				throw new Exception( "Create file: "+url+" failed." );
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		//RPC:
		try {
			InitialContext ctx = new InitialContext();
			UserManagerLocal userDao = (UserManagerLocal)ctx.lookup("FriendsAnywhere/UserManager/local");
			return userDao.updateUserProfile(userId, url) ? url : null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	//////////////////////////////////////////////////////////////////////////////

	private int userId;

}
